package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import com.qingcheng.util.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Welcome to the most Amazing IntelliJ IIIDEA.
 * Creat0r: ^_^ fffantianxing ^_^
 * Date: 2019-07-18
 * Time: 10:47
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private SkuService skuService;
    @Reference
    private CategoryService categoryService;
    @Autowired
    private PreferentialService preferentialService;

    @Override
    public List<Map<String, Object>> findCartList(String username) {
        System.out.println("从redis中查询。。。");
        List<Map<String, Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if (cartList == null) {
            cartList = new ArrayList<>();
        }
        return cartList;
    }

    @Override
    public void addCart(String skuId, String username, Integer num) {

        List<Map<String, Object>> cartList = findCartList(username);
        boolean flag = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (orderItem.getSkuId().equals(skuId)) {
                if (orderItem.getNum() <= 0) {
                    cartList.remove(map);
                    flag = true;
                    break;
                }
                orderItem.setNum(orderItem.getNum() + num);
                if (orderItem.getNum() <= 0) {
                    cartList.remove(map);
                    flag = true;
                    break;
                }
                Integer weight = orderItem.getWeight() / orderItem.getNum();
                orderItem.setWeight(orderItem.getNum() * weight);
                orderItem.setMoney(orderItem.getPrice() * orderItem.getNum());


                flag = true;
                break;
            }
        }
        if (flag == false) {//购物车不存在这件商品，添加商品信息
            Sku sku = skuService.findById(skuId);//查询sku信息

            if (sku == null) {
                throw new RuntimeException("商品信息有误");
            }
            if (!sku.getStatus().equals("1")) {
                throw new RuntimeException("商品状态不合法");
            }
            if (num < 1) {
                throw new RuntimeException("商品数量不合法");
            }

            OrderItem orderItem = new OrderItem();

            orderItem.setNum(num);//数量
            orderItem.setPrice(sku.getPrice());
            orderItem.setMoney(num * sku.getPrice());//金额
            orderItem.setSkuId(skuId);//skuId
            orderItem.setImage(sku.getImage());//图片
            orderItem.setName(sku.getName());//名字
            if (sku.getWeight() == null) {
                sku.setWeight(0);
            }
            orderItem.setWeight(num * sku.getWeight());//重量

            //设置分类信息
            orderItem.setCategoryId3(sku.getCategoryId());

            Category category3 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            if (category3 == null) {
                category3 = categoryService.findById(sku.getCategoryId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(sku.getCategoryId(), category3);
            }
            Integer categoryId2 = category3.getParentId();
            orderItem.setCategoryId2(categoryId2);

            Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(categoryId2);
            if (category2 == null) {
                category2 = categoryService.findById(categoryId2);
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(categoryId2, category2);
            }
            Integer categoryId1 = category2.getParentId();
            orderItem.setCategoryId1(categoryId1);

            Map map = new HashMap();
            map.put("item", orderItem);
            map.put("checked", true);//默认选中
            cartList.add(map);
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
    }

    @Override
    public void updateChecked(boolean checked, String skuId, String username) {
        List<Map<String, Object>> cartList = findCartList(username);
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())) {
                map.put("checked", checked);
                redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
            }
        }

    }

    @Override
    public void deleteCheckedCart(String username) {
        //获取未选中的商品
        List<Map<String, Object>> checkedCart = findCartList(username).stream().filter(cart -> (boolean) cart.get("checked") == false).collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, checkedCart);//将数据存入缓存
    }

    @Override
    public int preferential(String username) {

        //勾选的商品
        List<OrderItem> orderItems = findCartList(username)
                .stream()
                .filter(cart -> (boolean) cart.get("checked") == true)
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());

        //按分类聚合统计每个分类的金额
        Map<Integer, IntSummaryStatistics> cartMap = orderItems
                .stream()
                .collect(Collectors
                .groupingBy(OrderItem::getCategoryId3, Collectors
                .summarizingInt(OrderItem::getMoney)));

        //总共优惠金额
        int totalPreMoney = 0;
        for (Integer categoryId : cartMap.keySet()) {

            totalPreMoney += preferentialService.findPreMoneyByCategoryIdAndMoney(categoryId.longValue(),(int)cartMap.get(categoryId).getSum());
        }
        System.out.println(totalPreMoney);

        return totalPreMoney;
    }

    @Override
    public List<Map<String, Object>> findNewOrderList(String username) {

        //根据用户名查询
        List<Map<String, Object>> cartList = findCartList(username);
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            Sku sku = skuService.findById(orderItem.getSkuId());
            orderItem.setPrice(sku.getPrice());
            orderItem.setMoney(orderItem.getPrice()*orderItem.getNum());
        }

        //将更新后的数据加入缓存
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);

        return cartList;
    }
}
